package yfdc.douyin.download.network

import yfdc.douyin.download.NetWork
import okhttp3.Request
import okhttp3.HttpUrl.Companion.toHttpUrl
import org.jsoup.Jsoup
import yfdc.douyin.download.Utils
import java.util.concurrent.atomic.AtomicBoolean

class WorkFlow {
    fun interface CaptchaCallback {
        fun onCaptchaResult(suc: Boolean, go: String)
    }

    private var _callBack: CaptchaCallback? = null
    fun setCallBack(cpCallBk: CaptchaCallback?): WorkFlow {
        this._callBack = cpCallBk
        return this
    }

    private val netWork = NetWork.getInstance()
    private val executed = AtomicBoolean(false)
    /**
     * 1.parseUrl
     * 2.resolveYZMBody
     */
    fun parseUrl(url: String) {
        if (url.contains("v.douyin.com") || url.contains("www.iesdouyin.com")) {
            val req = Request.Builder()
                    .url(url.toHttpUrl())
                    .header("User-Agent", Utils.USER_AGENT)
                    .build()
            netWork.postHttp(req, {
                executed.set(true)
                resolveYZMBody(it)
            }) {
                executed.set(true)
            }
        }
    }

    private fun resolveYZMBody(it: Result<okhttp3.Response>?) {
        if (it === null || it.data == null) return
        val data = it.data
        _callBack?.onCaptchaResult(false, data.request.url.toString())
    }
}
